package io.gitee.capricorn.utils;


import io.gitee.capricorn.exception.EncryptedCharacterException;
import io.gitee.gemini.utis.StrUtil;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SecureUtil {

    public static final String MD5 = "MD5";
    public static final String SHA1 = "SHA1";
    public static final String SHA256 = "SHA256";

    private SecureUtil() {
    }

    /**
     * 字符串计算md5
     *
     * @param origin 原文
     * @return md5
     * @throws EncryptedCharacterException 计算字符不合规异常
     */
    public static String calcMD5(String origin) throws EncryptedCharacterException {
        if (StrUtil.isEmpty(origin)) {
            throw new EncryptedCharacterException("null or \"\" unable to encrypt");
        }
        return calcMD5(origin.getBytes());
    }

    /**
     * 比特流计算md5
     *
     * @param originBytes 加密原文
     * @return md5值
     */
    public static String calcMD5(byte[] originBytes) throws EncryptedCharacterException {
        if (originBytes == null || originBytes.length == 0) {
            throw new EncryptedCharacterException("null or [] unable to encrypt");
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(MD5);
            byte[] bytes = messageDigest.digest(originBytes);
            return byte2Hex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 计算文件md5值
     *
     * @param file 文件
     */
    public static String calcMD5(File file) throws IOException, EncryptedCharacterException {
        byte[] bytes = FileUtils.readFileToByteArray(file);
        return calcMD5(bytes);
    }


    /**
     * 字节转16进制
     *
     * @param bytes 需要转换的字符串
     * @return 转换结果
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        int temp;
        try {
            for (byte aByte : bytes) {
                temp = aByte;
                if (temp < 0) {
                    temp += 256;
                }
                if (temp < 16) {
                    result.append("0");
                }
                result.append(Integer.toHexString(temp));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


}
